#!/bin/bash

set -e

# Defaults
ENABLE_SHARED_TESTS=NO
SRCDIR="$PWD"
: ${TMPDIR:=/tmp}

if [ "$COMPILER" = clang ]; then
    export CC=/usr/bin/clang
else
    export CC=/usr/bin/gcc
fi

if [ "$OS_NAME" = "ubuntu-latest" ]; then
    if [ "$ARCH" = i386 ]; then
        ARCH_FLAGS="-m32"
        export PKG_CONFIG_PATH=/usr/lib/i386-linux-gnu/pkgconfig
    else
        ARCH_FLAGS=""
    fi
elif [ "$OS_NAME" = osx ]; then
    if [ "$ARCH" = i386 ]; then
        ARCH_FLAGS="-arch i386"
    else
        ARCH_FLAGS="-arch x86_64"
    fi
fi

build_autotools () {
  BUILDDIR=$(mktemp -d "$TMPDIR"/build-autotools-XXXXXX)
  echo "Using autotools to build in $BUILDDIR"
  echo "$ autogen.sh"
  "$SRCDIR"/autogen.sh
  cd "$BUILDDIR"
  echo "$ configure"
  CFLAGS="-g -O3 $ARCH_FLAGS" "$SRCDIR"/configure
  echo "$ make"
  make
  echo "$ make check"
  make check VERBOSE=1
  echo "$ make distcheck"
  make distcheck
}

build_cmake () {
  BUILDDIR=$(mktemp -d "$TMPDIR"/build-cmake-XXXXXX)
  echo "Using cmake to build in $BUILDDIR"
  cd "$BUILDDIR"
  echo "$ cmake"
  cmake "$SRCDIR" \
      -DCMAKE_BUILD_TYPE=RelWithDebInfo \
      -DCMAKE_C_FLAGS_RELWITHDEBINFO="-g -O3 $ARCH_FLAGS $EXTRA_FLAGS" \
      -DENABLE_SHARED_TESTS="$ENABLE_SHARED_TESTS"
  echo "$ make"
  make
  echo "$ make test"
  CTEST_OUTPUT_ON_FAILURE=1 make test
}

build_cmake_from_dist () {
  DISTDIR=$(mktemp -d "$TMPDIR"/build-dist-XXXXXX)
  echo "Using autotools to create dist tarball in $DISTDIR"
  "$SRCDIR"/autogen.sh
  cd "$DISTDIR"
  echo "$ configure"
  CFLAGS="-g -O3 $ARCH_FLAGS" "$SRCDIR"/configure
  echo "$ make dist"
  make dist
  # We should end up with exactly one *.tar.xz file
  TARBALL=$(ls *.tar.xz | head -n 1)
  UNPACKED=${TARBALL%.tar.xz}

  UNPACKEDDIR=$(mktemp -d "$TMPDIR"/build-unpacked-XXXXXX)
  echo "Unpacking dist tarball $UNPACKED into $UNPACKEDDIR"
  cd "$UNPACKEDDIR"
  tar xvf "$DISTDIR"/"$TARBALL"

  BUILDDIR=$(mktemp -d "$TMPDIR"/build-cmake-XXXXXX)
  echo "Using cmake to build from dist tarball in $BUILDDIR"
  cd "$BUILDDIR"
  echo "$ cmake"
  cmake "$UNPACKEDDIR"/"$UNPACKED" \
      -DCMAKE_BUILD_TYPE=RelWithDebInfo \
      -DCMAKE_C_FLAGS_RELWITHDEBINFO="-g -O3 $ARCH_FLAGS $EXTRA_FLAGS"
  echo "$ make"
  make
  echo "$ make test"
  CTEST_OUTPUT_ON_FAILURE=1 make test
}

# Flavors
case $FLAVOR in
  autotools)
    BUILDER=autotools
    ;;
  cmake)
    BUILDER=cmake
    ;;
  shared-cmake)
    BUILDER=cmake
    ENABLE_SHARED_TESTS=yes
    ;;
  fallback-u128)
    BUILDER=cmake
    EXTRA_FLAGS="$EXTRA_FLAGS -DCORK_CONFIG_HAVE_GCC_INT128=0"
    EXTRA_FLAGS="$EXTRA_FLAGS -DCORK_CONFIG_HAVE_GCC_MODE_ATTRIBUTE=0"
    ;;
  cmake-from-dist)
    BUILDER=cmake_from_dist
    ;;
  *)
    echo "Unknown build flavor $FLAVOR!" >&2
    exit 1
    ;;
esac

build_$BUILDER
